#include "dynamic_impl.h"

/////////////////////////////////////////////////////////////////////////////////////////
// 
namespace xos
{
    dynamic_impl::dynamic_impl()
    {
        m_hModule = 0;
    }

    dynamic_impl::~dynamic_impl()
    {
        term();
    }

    ////////////////////////////////////////////////////////////////////////////////////
    // 

    int dynamic_impl::init()
    {
        int nRet = 0;
        return nRet;
    }

    int dynamic_impl::term()
    {
        int nRet = 0;
        free();
        return nRet;
    }

    ////////////////////////////////////////////////////////////////////////////////////
    // 

    int dynamic_impl::load( const char * lpszFile )
    {
        int nRet = 0;

        WCHAR szFile[4096] = { 0 };
        WCHAR cfile[4096] = { 0 };

        if( 0 == nRet )
        {
            if( !lpszFile || ( 0 == strlen( lpszFile ) ) )
            {
                nRet = 1;
            }
        }

        if( 0 == nRet )
        {
            nRet = misc_tool::utf8_to_wchar( lpszFile, -1, cfile, sizeof( cfile ), 0 );
        }

        if( 0 == nRet )
        {
            wcscpy_s( szFile, cfile );
            wcscat_s( szFile, L".dll" );

            m_hModule = LoadLibraryW( szFile );

            if( !m_hModule )
            {
                nRet = 1;
            }
        }

        return nRet;
    }

    void * dynamic_impl::get_proc_by_name( const char * lpszProcName )
    {
        int nRet = 0;

        void * pRet = 0;

        if( 0 == nRet )
        {
            if( !m_hModule )
            {
                nRet = 1;
            }
        }

        if( 0 == nRet )
        {
            pRet = GetProcAddress( m_hModule, lpszProcName );

            if( !pRet )
            {
                nRet = 1;
            }
        }

        return pRet;
    }

    int dynamic_impl::free()    
    {
        int nRet = 0;

        if( m_hModule )
        {
            FreeLibrary( m_hModule );
            m_hModule = 0;
        }

        return nRet;
    }

    int dynamic_impl::release()
    {
        int nRet = 0;

        term();
        put_back_lock();

        return nRet;
    }
} // xos
